#include "device.h"
#include "softiic.h"

static int32_t IIC_Write(VirtualHardware_enum_t dev, void *data, uint32_t len, uint32_t param)
{
    uint8_t iic_addr = ((param & 0xFF) << 1);

    if (dev == vIIC_9)
    {
        return Softiic_Write(1, iic_addr, data, len);
    }
    else if (dev == vIIC_10)
    {
        return Softiic_Write(2, iic_addr, data, len);
    }
    else
    {
        return -1;
    }
}

static int32_t IIC_Read(VirtualHardware_enum_t dev, void *data, uint32_t len, uint32_t param)
{
    uint8_t iic_addr = ((param & 0xFF) << 1) | 1;

    if (dev == vIIC_9)
    {
        return Softiic_Read(1, iic_addr, data, len);
    }
    else if (dev == vIIC_10)
    {
        return Softiic_Read(2, iic_addr, data, len);
    }
    else
    {
        return -1;
    }
}

static int8_t IIC_Enable(VirtualHardware_enum_t dev)
{
    if (dev == vIIC_9)
    {
        Softiic_init(1);
    }
    else if (dev == vIIC_10)
    {
        Softiic_init(2);
    }
    return 0;
}

static int8_t IIC_Disable(VirtualHardware_enum_t dev)
{
    // printf("IIC_Disable %d \r\n",dev);
    if (dev == vIIC_9)
    {
        Softiic_deinit(1);
    }
    else if (dev == vIIC_10)
    {
        Softiic_deinit(2);
    }
    return 0;
}

static void IIC_Init(void)
{
    printf("iic init\r\n");
    IIC_Enable(vIIC_9);
    IIC_Enable(vIIC_10);
    Device_stu_t *dcb = Device_GetDeviceCtrlBlock(vIIC);
    dcb->write = IIC_Write;
    dcb->read = IIC_Read;
    dcb->enable = IIC_Enable;
    dcb->disable = IIC_Disable;
}
INIT_BOARD_EXPORT(IIC_Init);
